/**    
 * @Description:博客园地址：https://www.cnblogs.com/zumengjie/      
 * @author:顶风少年   
 * @date:   2021年4月1日 下午10:55:40
 */
package datang.dtdb.parsing;

import java.io.InputStream;
import java.util.Properties;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import datang.dtdb.exceptions.XMLParserException;

/**
 * xml解析工具类
 */
public class XPathParser {

	/**
	 * 获取Document
	 */
	public static Document document(InputStream inputStream) {
		DocumentBuilderFactory newInstance = DocumentBuilderFactory.newInstance();
		try {
			DocumentBuilder builder = newInstance.newDocumentBuilder();
			return builder.parse(inputStream);
		} catch (Exception e) {
			throw new XMLParserException("获取Document失败", e);
		}

	}

	/**
	 * 获取RootElement
	 */
	public static Element rootElement(Document document) {
		return document.getDocumentElement();
	}

	/**
	 * 获取指定节点（single）如果获取不到会返回null
	 */
	public static Node singleEleByTagName(Node element, String tagName) {
		NodeList nodeList = listEleByTagName(element, tagName);
		if (nodeList == null) {
			return null;
		}
		return nodeList.item(0);
	}

	/**
	 * 获取指定节点群，如果获取不到返回null
	 */
	public static NodeList listEleByTagName(Node element, String tagName) {
		Element e = (Element) element;
		NodeList eleList = e.getElementsByTagName(tagName);
		if (eleList.getLength() == 0) {
			return null;
		}
		return eleList;
	}

	/**
	 * 获取标签上的指定属性
	 */
	public static String eleAttr(Node element, String attrName) {
		Element e = (Element) element;
		boolean hasAttribute = e.hasAttribute(attrName);
		if (hasAttribute) {
			String value = e.getAttribute(attrName);
			return value;
		} else {
			return null;
		}
	}

	/**
	 * 将指定标签下的子标签<property>封装成Properties对象 如果没有子标签<property>返回null。有则将每一个<property>中
	 * 的name和value封装
	 */
	public static Properties eleProperties(Node element) {
		NodeList propertyList = listEleByTagName(element, "property");
		if (propertyList == null || propertyList.getLength() <= 0) {
			return null;
		}
		Properties properties = new Properties();
		for (int i = 0; i < propertyList.getLength(); i++) {
			Node propertie = propertyList.item(i);
			String name = eleAttr(propertie, "name");
			String value = eleAttr(propertie, "value");
			if (name != null || value != null) {
				properties.put(name, value);
			}
		}
		return properties;
	}

	/**
	 * 获取指定标签下的所有次级标签
	 */
	public static NodeList listEle(Node element) {
		Element e = (Element) element;
		NodeList eleList = e.getChildNodes();
		if (eleList.getLength() == 0) {
			return null;
		}
		return eleList;
	}
}
